package org.musicPlayerServer.business;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Collections;

public class FileManager {


    public String getNext(String currentFile) {
	String nextFile =null;
	File file = new File(currentFile);
	if(file.exists()&&file.isFile()){


	    nextFile  = findNextFile(file);
	    if(nextFile==null){
		nextFile = findNextFileFromNextFolder(file);
	    }

	}

	return nextFile;
    }

    String findNextFileFromNextFolder(File file) {
	File nextFile = null;
	File nextFolder = findNextFolder(file.getParentFile());
	if(nextFolder!=null){
	    nextFile = findFirstFileFromFolder(file);
	}
	return nextFile==null?null:nextFile.getAbsolutePath();
    }

    File findFirstFileFromFolder(File file) {
	// TODO Auto-generated method stub
	return null;
    }

    File findNextFolder(File folder) {
	File parent = folder.getParentFile();
	File[] childFolders = parent.listFiles(new FileFilter() {

	    @Override
	    public boolean accept(File file) {
		return file.isDirectory();
	    }
	}); 
	String fileName = folder.getName();
	File result = null;
	Integer n = childFolders.length;
	Integer i = 0;
	while(result==null&&i<n){
	    if(childFolders[i].equals(fileName)){
		if (i+1<n){
		    result = childFolders[i+1];
		}
	    }
	    i++;
	}
	return result;
    }

    String findNextFile(File file) {
	File parent = file.getParentFile();
	String[] files = parent.list(new FilenameFilter(){
	    @Override
	    public boolean accept(File dir, String name) {
		return name.endsWith(".mp3");

	    }
	});
	Collections.sort(Arrays.asList(files));
	String fileName = file.getName();
	String result = null;
	Integer n = files.length;
	Integer i = 0;
	while(result==null&&i<n){
	    if(files[i].equals(fileName)){
		if (i+1<n){
		    result = files[i+1];
		}
	    }
	    i++;
	}
	return result==null?null:parent.getAbsolutePath()+"/"+result;
    }

   



}
